<?php
defined('IN_XLP') or exit('Access Denied');

class taskModel extends Model {

	function __construct() {
		parent::__construct();
	}

	/*
	 * 获取任务发布者所有类型奖品
	 */
	public function getReward($uid) {
		$uid = intval($uid);
		if($uid) {
			$uid .= ',0';   //积分和结邻币uid为0
		}
		$rs = M('task_reward')
			->field('`id`,`reward_name`')
			->where("`poster_uid` in ($uid)")
			->findAll();
		return $rs;
	}

	/*
	 * 根据奖品类型ID获取奖品名称
	 */
	public function getRewardName($reward_type) {
		$type_id = intval($reward_type);
		$rs = M('task_reward')
			->field('`reward_name`')
			->where(array('id'=>$type_id))
			->find();
		return empty($rs) ? '' : $rs['reward_name'];
	}

	/*
	 * 新增奖品
	 */
	public function addNewReward($poster_uid, $reward_name) {
		$rs = M('task_reward')
			->field('`id`')
			->where(array(
				'poster_uid'  => $poster_uid,
				'reward_name' => $reward_name))
			->find();
		if( $rs || in_array($reward_name, array('积分','结邻币')) ) {
			return -1; //该发布者已经添加过此奖品
		}
		$rs = M('task_reward')->insert(
			array(
				'poster_uid'  => $poster_uid,
				'reward_name' => $reward_name,
				'add_time'    => TIME,
			)
		);
		return $rs===false ? false : $rs;
	}

	/*
	 * 增加阅读次数
	 */
	public function readTask($task_id) {
		M('task')->update(
			"`read_time`=`read_time`+1",
			array('id'=>$task_id)
		);
	}

	/*
	 * 浏览分享页面 添加奖励
	 */
	public function userGetReward($task_id, $uid, $openid) {
		$rs = M('task_log')
			->field('id')
			->where(array('task_id'=>$task_id, 'uid'=>$uid, 'helper_openid'=>$openid))
			->find();
		//是否被同一个帐号浏览过
		if($rs) {
			return false;
		} else {

			//添加浏览记录
			M('task_log')->insert(
				array(
					'uid'           => $uid,
					'task_id'       => $task_id,
					'helper_openid' => $openid,
					'helper_ip'     => getUserIp(),
					'event_time'    => TIME,
				)
			);
			//任务是否进行中
			$rs = $this->isOnline($task_id);
			if(!$rs) return false;

			$user_info = M('task_user')->field('`state`')->where(array('uid'=>$uid))->find();
			if($user_info['state'] == 1) {  //未冻结

				//推广次数增加
				M('task')->update(
					"`promotion_time`=`promotion_time`+1",
					array('id'=>$task_id)
				);

				M('task_statistic')->update(
					"`promotion_time`=`promotion_time`+1",
					array('task_id'=>$task_id,'uid'=>$uid)
				);

				//是否达到今日奖励上限
				$is_limited = $this->checkRewardLimit($task_id, $uid);
				if(!$is_limited) {
					$rs = M('task_statistic')->field('`promotion_time`')->where(array('task_id'=>$task_id,'uid'=>$uid))->find();
					$promotion_time = $rs['promotion_time'];
					//处理奖品
					$this->processReward($task_id, $promotion_time, $uid);
				}
				
			}

		}
	}

	/*
	 * 根据openid判断用户是否关注
	 */
	public function getUserByOpenid($openid) {
		$rs = M('user_bind')
			->field('`uid`')
			->where(array('keyid'=>$openid))
			->find();
		if($uid = $rs['uid']) {
			$rs = M('user')->field('`status`')->where(array('uid'=>$uid))->find();
			if($rs['status'] == 0) { //已取消关注
				return 0;
			} else {
				return $uid;
			}
		} else {
			return false;
		}
	}

	/*
	 * 检查任务状态
	 */
	public function checkTask($task_id) {
		$rs = M('task')
			->field('`is_del`')
			->where(array('id'=>$task_id))
			->find();
		if($rs['is_del'] == 1) {	//任务已经删除
			return false;
		} else {
			return true;
		}
	}

	//任务是否进行中
	public function isOnline($task_id) {
		$rs = M('task')->field('`time_start`,`time_end`,`is_del`')->where(array('id'=>$task_id))->find();
		if($rs) {
			if( $rs['time_start']>TIME || ($rs['time_end']>0 && $rs['time_end']<TIME) || $rs['is_del']==1 ) {
				return false;
			}
		} else {
			return false;
		}
		return true;
	}

	/*
	 * 处理奖品数量
	 */
	public function processReward($task_id, $promotion_time, $uid) {
		$rs = M('task')->field('`reward_type`,`reward_total`,`reward_owner`,`reward_left`,`reward_rate`,`reward_threshold`,`time_expire`')->where(array('id'=>$task_id))->find();
		$reward_rate  = explode(':', $rs['reward_rate']);	//奖品汇率
		$threshold    = intval($rs['reward_threshold']);	 //减少奖品阈值
		$reward_total = $rs['reward_total'];
		$reward_left  = $rs['reward_left'];	  //剩余奖品


		//设置了任务时限
		if($rs['time_expire'] > 0) {
			$time_add = M('task_statistic')
				->field('`time_add`')
				->where( array("task_id"=>$task_id,"uid"=>$uid) )
				->find();
			$time_add = $time_add['time_add'];
			if( $time_add + $rs['time_expire'] < TIME ) {	//任务超时
				return false;
			}
		}

		$is_int = ($promotion_time - $threshold) / $reward_rate[1];
		if( is_int($is_int) && $promotion_time > 0 ) {	//达到阈值减少奖品库存
			if($reward_left >= $reward_rate[0]) {
				$reward_left -= $reward_rate[0];
				
				//设置了阈值
				if($threshold > 0) {
					$reward_owner = json_decode($rs['reward_owner'], true);
					if(empty($reward_owner)) {
						$reward_owner = array();
					}
					array_push($reward_owner, $uid);
					$rs['reward_owner'] = json_encode($reward_owner);
				}

				M('task')->update(
					array('reward_left'=>$reward_left, 'reward_owner'=>$rs['reward_owner']),
					array('id'=>$task_id)
				);

			}
		}

		$is_int = $promotion_time / $reward_rate[1];
		if( is_int($is_int) && $promotion_time > 0 ) {  //达到兑换标准
			//获得奖励数量是否超出奖励总数
			$reward_get_total = M('task_statistic')->query("SELECT sum(reward_get) AS sum FROM __TABLE__ where `task_id`={$task_id}", true);
			$reward_get_total = $reward_get_total['sum'];
			if($reward_get_total + $reward_rate['0'] > $reward_total) {
				return false;
			}

			if($threshold > 0) {
				$reward_owner = json_decode($rs['reward_owner'], true);
				if(!empty($reward_owner) && in_array($uid, $reward_owner)) {
					foreach ($reward_owner as $k => $v) {
						if($v==$uid) {
							unset($reward_owner[$k]);
							break;
						}
					}
					$reward_owner = json_encode($reward_owner);

					M('task')->update(
						array('reward_owner'=>$reward_owner),
						array('id'=>$task_id)
					);

					M('task_statistic')->update(
						"`reward_get`=`reward_get`+{$reward_rate['0']}",
						array("task_id"=>$task_id,"uid"=>$uid)
					);
				}
			} else {
				M('task_statistic')->update(
					"`reward_get`=`reward_get`+{$reward_rate['0']}",
					array("task_id"=>$task_id,"uid"=>$uid)
				);
			}
			
			//积分结邻币另外统计用以缓存和排行 1:积分 2:结邻币
			if( in_array($rs['reward_type'], array(1,2)) ) {
				$this->rewardCache($uid, $rs['reward_type'], $reward_rate['0']);
			}

		}
		
	}



	/*
	 * 检查用户是否达到每日奖励上限
	 */
	public function checkRewardLimit($task_id, $uid) {
		//奖品上限
		$rs = M('task')->field('`reward_limit`')->where(array('id'=>$task_id))->find();
		$reward_limit = $rs['reward_limit'];
		if($reward_limit <= 0) {
			return false;
		}

		//奖品汇率
		$task_info = M('task_statistic')
			->field('`reward_rate`')
			->where(array('task_id'=>$task_id, 'uid'=>$uid))
			->find();
		//奖品数量 ：推广次数
		$reward_rate = explode(':', $task_info['reward_rate']);
		//时间范围
		$from = strtotime(date('Y-m-d', TIME));
		$to   = $from + 3600*24;

		$rs = M('task_log')
			->field('`id`')
			->where("`task_id`=$task_id AND `uid`=$uid AND `event_time` BETWEEN $from AND $to")
			->findAll();
		$promotion_time = count($rs);
		$reward_total   = $reward_rate[0] * floor($promotion_time / $reward_rate[1]);

		return $reward_limit >= $reward_total ? false : true;
	}

	/*
	 * 检查用户是否达到每天任务上限
	 */
	public function checkTaskLimit($uid) {
		$rs = M('task_user')
			->field('`task_at_today`,`task_update_time`')
			->where(array('uid'=>$uid))
			->find();

		if(empty($rs)) {	//用户尚未领取过任务
			$rs = M('task_user')->insert(array(
				'uid' => $uid,
				'task_at_today' => 1,
				'task_update_time' => TIME,
				'reg_time' => TIME,
			));
			if($rs===false) return -1;  //插入新用户失败
		} else {	//检查任务上限
			$today = date('Y-m-d', TIME);
			$update_time = date('Y-m-d', $rs['task_update_time']);
			
			if($update_time === $today) {   //今日已领取过任务
				if($rs['task_at_today'] < 3) {  //尚未达到上限
					M('task_user')->update(
						"`task_at_today`=`task_at_today`+1, `task_update_time`=".TIME,
						"`uid`=$uid"
					);
					return true;
				} else {	//达到上限
					return false;
				}
			} else {	//当日尚未领取任务
				M('task_user')->update(
					array(
						'task_at_today'	=> 1,
						'task_update_time' => TIME,
					),
					array('uid'=>$uid)
				);
				return true;
			}
		}

	}


	/*
	 * 用户是否领取过该任务
	 */
	public function checkUserTask($uid, $task_id) {
		$rs = M('task_statistic')
			->field('`promotion_code`')
			->where(array('uid'=>$uid, 'task_id'=>$task_id))
			->find();
		return $rs ? $rs['promotion_code'] : false;
	}

	/*
	 * 新建用户任务
	 */
	public function addUserTask($uid, $task_id) {
		$rs = M('task_statistic')
			->field('`uid`,`promotion_code`')
			->where(array('uid'=>$uid, 'task_id'=>$task_id))
			->find();
		if($rs) {   //已领取过该任务
			return $rs['promotion_code'];
		} else {	//新添任务
			$task_info = M('task')
				->field('`reward_type`,`reward_rate`')
				->where(array('id'=>$task_id))
				->find();
			//推广码
			$promotion_code = setEnocde($task_id."\t".$uid);
			$rs = M('task_statistic')->insert(
				array(
					'task_id'        => $task_id,
					'uid'            => $uid,
					'reward_type'    => $task_info['reward_type'],
					'reward_rate'    => $task_info['reward_rate'],
					'time_add'       => TIME,
					'promotion_code' => $promotion_code,
				)
			);
			if($rs) {
				//参与人数加一
				M('task')->update(
					"`partin_num`=`partin_num`+1",
					array('id'=>$task_id)
				);
				//领取任务总数加一
				M('task_user')->update(
					"`task_total`=`task_total`+1",
					array('uid'=>$uid)
				);
			}
			return $rs ? $promotion_code : false;
		}
	}


	/**
	 * 积分和结邻币缓存 给予适当人工审核时间
	 * @param  int $uid		   用户UID
	 * @param  int $reward_type   奖励类型 1：积分 2：结邻币
	 * @param  int $reward_amount 奖励数量	 
	 */
	public function rewardCache($uid, $reward_type, $reward_amount) {
		$today = date('Y-m-d', TIME);
		$rs = M('task_user')
			->field('`reward_cache`')
			->where(array('uid'=>$uid))
			->find();

		if(empty($rs['reward_cache'])) {	//新建缓存
			$cache = array(
				$today => array(
					$reward_type => $reward_amount
				)
			);
		} else {	//更新缓存
			$cache = json_decode($rs['reward_cache'], true);
			$hasToday = false;  //有无当天的积分缓存记录
			foreach ($cache as $k => $v) {
				if($k === $today) {
					if(isset($v[$reward_type])) {
						$cache[$k][$reward_type] += $reward_amount;
					} else {	//新建当日积分类型
						$cache[$k] += array($reward_type=>$reward_amount);
					}
					$hasToday = true;
					break;
				}
			}
			if(!$hasToday) {	//新建当日的积分缓存
				$cache += array($today=>array($reward_type=>$reward_amount));
			}
		}

		M('task_user')->update(
			array('reward_cache'=>json_encode($cache)),
			array('uid'=>$uid)
		);
	}

	/*
	 * 发放积分和结邻币缓存
	 */
	public function rewardFlushCache($uid) {

		$reward_flush_time = myCookie('reward_flush');
		if($reward_flush_time) {
			$day  = date('Y-m-d', $reward_flush_time);
			$hour = date('H', $reward_flush_time);
			$new_day  = date('Y-m-d', TIME);
			$new_hour = date('H', TIME);

			//当天已经刷过或者尚未超过审核时间
			if( $day == $new_day && ($hour >=18 || $new_hour < 18) ) {
				return false;
			}
		}

		$delay = (24+18)*3600;	//昨天的奖励第二天18点后发放
		// $delay = 0;

		$rs = M('task_user')
			->field('`reward_cache`,`state`')
			->where(array('uid'=>$uid))
			->find();

		if(!$rs['state']) { //用户被冻结
			return false;
		}

		if( !empty($rs['reward_cache']) ) {
			$cache = json_decode($rs['reward_cache'], true);
			if(empty($cache)) {
				return false;
			}
			$credit_total = 0;
			$coin_total   = 0;
			foreach ($cache as $k => $v) {
				if( strtotime($k) + $delay < TIME ) {   //超过审核时间
                    if(isset($v['1'])) $credit_total += $v['1'];    //积分
                    if(isset($v['2'])) $coin_total += $v['2'];    //结邻币
                    unset($cache[$k]);
				}
			}
			//发放奖励            
            if($credit_total > 0) {
            	$this->setUserScore($uid, $credit_total, 1);
            }
            if($coin_total > 0) {
            	$this->setUserScore($uid, $coin_total, 2);
            }
            //更新缓存
            M('task_user')->update(
            	array('reward_cache'=>json_encode($cache)),
            	array('uid'=>$uid)
            );
            myCookie('reward_flush', TIME, 3600*24);
		} else {
			return false;
		}

	}

	/**
	 * 增加用户积分or结邻币
	 * @param int $uid          用户uid
	 * @param int $score_amount 奖励数量
	 * @param int $score_type   奖励类型 1：积分 2：结邻币
	 */
	public function setUserScore($uid,$score_amount,$score_type) {
		$data = array();
        $data['uid']      = $uid;
        $data['act']	  = 1;	//增加积分or结邻币
        $data['credit']	  = intval($score_amount);
        $data['content']  = '分享奖励';
		$data['infotime'] = TIME;

		if ($score_type==1) {	//增加积分

			M('task_user')->update(
				"`reward_credit`=`reward_credit`+{$data['credit']}",
				array('uid'=>$uid)
			);
			M('user')->where(array('uid' => $data['uid']))->setInc('event_credit', $data['credit']);
			M('event_credit_log')->insert($data);

		} else if($score_type==2) {		//增加结邻币

			M('task_user')->update(
				"`reward_coin`=`reward_coin`+{$data['credit']}",
				array('uid'=>$uid)
			);
			M('user')->where(array('uid' => $data['uid']))->setInc('shopping_credit', $data['credit']);
			M('shopping_credit_log')->insert($data);
		}
	}

}